#include <memory>
#include <cctype>
#include <algorithm>
#include "TcpServe.hpp"
#include "Daemon.hpp"
#include "Daemon.hpp"
#include "TcpServe.hpp"
using namespace std;

void Usage(string proc)
{
    cout<<"Usage:\n\t"<<proc<<"local_port"<<endl;
}
void Interact(int sockfd,const string &in)
{
    char buffer[1024];
    ssize_t n=read(sockfd,&buffer,sizeof(buffer))-1;
    if(n>0)
    {
        buffer[n]=0;
        write(sockfd,in.c_str(),in.size());//全双工通信
    }
    else if(n==0)
    {
        lg.LogMessage(Info,"client quit....\n");
    }
    else
    {
        lg.LogMessage(Error,"read socket error,errno code:%d,error string is %s\n",errno,strerror(errno));
    }
}

void Ping(int sockfd,InetAddr addr)
{
    lg.LogMessage(Debug,"%s select %s success,fd:%d\n",addr.PrintDebug().c_str(),"ping",sockfd);
    string message;
    Interact(sockfd,"Pong");
}
void Transform(int sockfd,InetAddr addr)//大小写转换
{
    lg.LogMessage(Debug,"%s select %s success,fd:%d",addr.PrintDebug().c_str(),"Thranform",sockfd);
    char message[128];
    int n=read(sockfd,&message,sizeof(message)-1);
    if(n>0)
    {
        message[n]=0;
    }
    else
    {
        lg.LogMessage(Error,"读取失败\n");
    }
    string messagebuf=message;
    transform(messagebuf.begin(),messagebuf.end(),messagebuf.begin(),[](unsigned char c){return toupper(c);});
    write(sockfd,messagebuf.c_str(),messagebuf.size());
}

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        Usage(argv[0]);
        return Usage_Err;
    }
    uint16_t port=stoi(argv[1]);
    //Deamon(false,false);//守护进程
    //lg.Enable(ClassFile);//信息记录形式为分文件
    unique_ptr<TcpServer> tsvr=make_unique<TcpServer>(port);

    //关联
    tsvr->RegisterFunc("Ping",Ping);
    tsvr->RegisterFunc("Transform",Transform);

    tsvr->Init();
    cout<<"运行到这里了吗？？"<<endl;

    tsvr->Start();
    return 0;
}
